﻿using System;
using System.Web;
using Microsoft.ServiceHosting.ServiceRuntime;

namespace BlogEngine.Core.Web.HttpModules
{
    public class PortChangeModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.EndRequest += OnEndRequest;
        }

        private static void OnEndRequest(object sender, EventArgs e) // TODO: Called On Cassini, but not on Azure => Useless? + I don't like this implementation; cf. Utils.AbsoluteWebRoot + What if it is a redirection to an external website?
        {
            HttpContext context = ((HttpApplication)sender).Context;
            HttpResponse response = context.Response;
            if ( response.IsRequestBeingRedirected )
            {
                var oldUri = new Uri(response.RedirectLocation, UriKind.Absolute);
                int port = oldUri.Port;
                if (RoleManager.IsRoleManagerRunning)
                //if (port != 80 &&  port != 81)
                {
                    string newUri = oldUri.GetComponents(UriComponents.Scheme, UriFormat.Unescaped) +
                        "://" +
                        oldUri.GetComponents(UriComponents.Host, UriFormat.Unescaped) +
                        ((port != 80 && port != 20000)?":81/":"") + 
                        oldUri.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
                    //response.Redirect(newUri, true);
                    response.RedirectLocation = newUri;
                }

            }
        }
    }
}
